package com.mark.mall.web.platform.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.mark.mall.common.constans.PlatformConstant;
import com.mark.mall.common.myException.MyException;
import com.mark.mall.common.resultBean.R;
import com.mark.mall.web.platform.entity.Product;
import com.mark.mall.web.platform.mapper.ProductMapper;
import com.mark.mall.web.platform.service.ElasticSearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author admin
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ElasticSearchServiceImpl implements ElasticSearchService {
    private final RestHighLevelClient restHighLevelClient;
    private final ProductMapper productMapper;
    @Override
    public R<Boolean> createIndex(String indexName) throws IOException {
        if (StrUtil.isBlank(indexName)) {
            throw new MyException("参数缺失，请核实！");
        }
        CreateIndexRequest createIndex = new CreateIndexRequest(indexName);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndex, RequestOptions.DEFAULT);
        return createIndexResponse.isShardsAcknowledged() ? new R<>("创建成功！") : new R<>("创建失败");
    }

    @Override
    public R<Boolean> bulkGoods() throws IOException {
        BulkRequest request = new BulkRequest(PlatformConstant.INDEX_NAME);
        List<Product> list = productMapper.selectList(null);
        if (list != null && list.size() > 0) {
            list.forEach(product -> {
                request.add(
                        new IndexRequest(PlatformConstant.INDEX_NAME)
                                .source(JSON.toJSONString(product), XContentType.JSON)
                );
            });
        }
        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        return !bulk.hasFailures() ? new R<>("添加成功！") : new R<>("添加失败");
    }
}
